import { NextResponse } from 'next/server';
import { query } from '@/utils/db';
import { RowDataPacket } from 'mysql2/promise';
import jwt from 'jsonwebtoken';

/**
 * 发布需求API
 * POST /api/enterprise/resources/needs
 * 需要登录且为企业管理员
 */
export async function POST(request: Request) {
  try {
    // 1. 验证用户是否已登录
    const authHeader = request.headers.get('Authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 2. 解析token
    const token = authHeader.substring(7); // 去掉"Bearer "前缀
    const secret = process.env.JWT_SECRET || 'your-secret-key';
    
    let decodedToken;
    try {
      decodedToken = jwt.verify(token, secret);
    } catch (error) {
      return NextResponse.json(
        { success: false, message: '无效的令牌' },
        { status: 401 }
      );
    }

    // 3. 获取用户信息
    const userId = (decodedToken as any).id;
    
    // 4. 查询用户是否为企业管理员
    const userQuery = `
      SELECT u.id, u.is_company_admin, c.id as company_id, c.name as company_name
      FROM users u 
      LEFT JOIN companies c ON u.id = c.admin_id
      WHERE u.id = ?
    `;
    const [userResult] = await query<RowDataPacket[]>(userQuery, [userId]);
    
    if (!userResult || !userResult.is_company_admin) {
      return NextResponse.json(
        { success: false, message: '只有企业管理员才能发布需求' },
        { status: 403 }
      );
    }
    
    // 5. 获取请求体数据
    const { title, description, type, tags } = await request.json();
    
    // 验证必填字段
    if (!title || !description || !type) {
      return NextResponse.json(
        { success: false, message: '标题、描述和类型为必填项' },
        { status: 400 }
      );
    }
    
    // 6. 保存需求数据
    const insertQuery = `
      INSERT INTO enterprise_cooperation_needs (
        company_id, title, description, type, tags, is_active, created_by
      ) VALUES (?, ?, ?, ?, ?, ?, ?)
    `;
    
    const tagsString = Array.isArray(tags) ? tags.join(',') : '';
    
    const result = await query(insertQuery, [
      userResult.company_id,
      title,
      description,
      type,
      tagsString,
      1, // 默认为激活状态
      userId
    ]);
    
    return NextResponse.json({
      success: true,
      message: '需求发布成功',
      needId: (result as any).insertId
    });
  } catch (error) {
    console.error('发布需求失败:', error);
    return NextResponse.json(
      { success: false, message: '发布需求失败' },
      { status: 500 }
    );
  }
} 